<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>我要连SOCKET</title>
    <base>
    <script src="https://cdn.bootcss.com/jquery/3.4.0/jquery.min.js"></script>
    <script src="https://cdn.bootcss.com/socket.io/2.2.0/socket.io.js"></script>
    <style>
        body {
            padding: 20px;
        }
        #console {
            height: 450px;
            overflow: auto;
        }
        .msg-color {
            color: green;
        }
    </style>
</head>

<body>
<div id="console" class="well"></div>


<div id="conversationDiv">
    <labal>给系统推消息</labal>
    <input type="text" id="content"/>
    <button id="btnSendToSystem" onclick="sendSys();">发送</button>
</div>


</body>
<script type="text/javascript">
    var socket;
    connect();

    function connect() {
        var userFlag = 'user_PU';
        var opts = {
            query: 'userFlag=' + userFlag
        };
        socket = io.connect('http://localhost:8503', opts);
        socket.on('connect', function () {
            console.log("连接成功");
            output('当前用户是：' + userFlag );
            output('<span class="msg-color">连接成功了。</span>');
        });
        socket.on('disconnect', function () {
            output('<span class="msg-color">下线了。 </span>');
        });

        socket.on('CHANNEL_STUDENT', function (data) {
            let msg= JSON.stringify(data)
            output('收到学生频道消息了：' + msg );
            console.log(data);

        });
        socket.on('CHANNEL_SYSTEM', function (data) {
            let msg= JSON.stringify(data)
            output('收到系统全局消息了：' + msg );
            console.log(data);

        });

    }

    function sendSys() {
        console.log('发送消息给服务端');
        var content = document.getElementById('content').value;

        socket.emit('CHANNEL_SYSTEM',JSON.stringify({
            'content': content,
            'from': 'user_PU'
        }));

    }
    function output(message) {
        var element = $("<div>" + message + "</div>");
        $('#console').prepend(element);
    }

</script>
</html>
